require("./utils/reWriteFuntions.js");
// require("./utils/mockSdk.js");
const logger = require("./services/logService.js");
const lmfService = require("./services/lmfService.js");
const Promise = require('./utils/es6-promise.min.js');
const CONFIG = require('./config.js');
const WxParse= require('/components/wxParse/wxParse.js');
const topTips = require('/templates/toptips/index.js');



function checkDebug() {
  if (!wx.getClipboardData) {
    return false;
  }
  wx.getClipboardData({
    success: function (res) {
      if (res.data == '小白,打开调试模式') {
        wx.setEnableDebug({
          enableDebug: true
        })
      }
      if (res.data == '小白,关闭调试模式') {
        wx.setEnableDebug({
          enableDebug: false
        })
      }
    }
  })
}

App({
  Api: lmfService,
  CONFIG: CONFIG,
  WxParse: WxParse,
  topTips: topTips,
  onShow: function () {
    checkDebug();
  },
  onLaunch(options) {
    // wx.clearStorageSync();
   
    var storageInfo = wx.getStorageInfoSync() || [];
    storageInfo.keys.forEach(function (item, i) {
        wx.removeStorageSync(item);
    })

    wx.setStorageSync('lmf-onLaunch', false);
    logger(options);
    this.getUserInfo();
  },
  getUserInfo() {
    var _this = this;

    if (_this.globalData.openid) {
      return Promise.resolve(_this.globalData.openid)
    }
    return new Promise((resolve, reject) => {
      wx.getUserInfo({
        success: resolve,
        fail: reject
      })
    })
      .then((res) => {
        if (res.errMsg != 'getUserInfo:ok') {
          throw  { code: 1000, msg: '获取用户信息失败' }
        }
      
        wx.setStorageSync('userInfo', res.userInfo);
       
        return new Promise((resolve, reject)=> {
          wx.login({
            success: function(info){
              info.userInfo = res.userInfo;
              resolve(info);
            },
            fail: reject
          })
        })
      })
      .then((res) => {
  
        if (res.errMsg != 'login:ok') {
          throw  { code: 1000, msg: '登录失败' }
        }
        return lmfService.get_openid(res);
      })
      .then((res) => {

        // openid = "obDIV0dX-7APmPBjwQC2toa6MCeg";
     
        if (!res.open_id) {
          throw  { code: 1002, msg: '获取openid失败' }
        }
        wx.setStorageSync('openid', _this.globalData.openid = res.open_id);
        return res;
      })
      .then((res) => {
        wx.setStorageSync('lmf-onLaunch', true);

        return new Promise((resolve, reject) => {
          this.Api.post('/iNews/uploadUserInfor', {
            open_id: res.open_id,
            wechatName: res.userInfo.nickName,
            photoUrl: res.userInfo.avatarUrl,
          })
        
        })
      })
      .catch((error) => {
        console.error(error);
      });
  },
  globalData: {
    openid: null
  },
  onReachBottom() { }
})